package com.gz.mylife.im;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.List;
import java.util.UUID;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import com.gz.mylife.Define;
import com.gz.mylife.im.ImageRequest.UploadListener;
import com.gz.mylife.util.ToastUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;

/**
 * 
 * @author 陈希然
 * ┏┓　　　┏┓
┏┛┻━━━┛┻┓
┃　　　　　　　┃ 　
┃　　　━　　　┃
┃　┳┛　┗┳　┃
┃　　　　　　　┃
┃　　　┻　　　┃
┃　　　　　　　┃
┗━┓　　　┏━┛
     ┃　　　┃   草泥马保佑　　　　　　　　
     ┃　　　┃   代码无BUG！
     ┃　　　┗━━━┓
     ┃　　　　　　　┣┓
     ┃　　　　　　　┏┛
     ┗┓┓┏━┳┓┏┛
        ┃┫┫　 ┃┫┫
        ┗┻┛　 ┗┻┛
 *
 */
public class ChatSessionService {

	private ListView mListView;
	private ChatSession mActivity;
	private ChatSessionAdapter mAdapter;
	private List<IMessage> mMessages;
	private RefreshHandler mHandler;
	private String TAG = "ChatSessionService";
	private static final int  MSG_LOSE_INFO = 101;
	private static final int  MSG_NO_FRIEND = 102;
	
	public ChatSessionService() {
		mHandler =new RefreshHandler(this);
	}
	
	public static class Builder {
		private ChatSession mActivity;
		private List<IMessage> mMessages;
		private ChatSessionAdapter mAdapter;
		private ListView mListView;
		
		public Builder setActivity(ChatSession activity){
			mActivity = activity;
			return this;
		}
		
		public Builder setDataList(List<IMessage> messages){
			mMessages = messages;
			return this;
		}
		
		public Builder setListView(ListView listView){
			mListView = listView;
			return this;
		}
		
		public Builder setAdapter(ChatSessionAdapter adapter){
			mAdapter = adapter;
			return this;
		}
		
		public ChatSessionService build(){
			ChatSessionService chatService = new ChatSessionService();
			chatService.mActivity = this.mActivity;
			chatService.mMessages = this.mMessages;
			chatService.mListView = this.mListView;
			chatService.mAdapter = this.mAdapter;
			return chatService;
		}
	} 
	
	// 创建消息
	private IMessage createMessage(int showType,int pmid,int to,String content){
		IMessage message = new IMessage();
		message.setFromUid(IAuth.getInstance().loadUserInfo().getUid());
		message.setGender(IAuth.getInstance().loadUserInfo().getGender());
		message.setToUid(to);
		message.setPmid(pmid);
		message.setContent(content);
		message.setComMsg(true);
		message.setShowType(showType);
		message.setMyType(0);
		message.setDateline(System.currentTimeMillis()/1000);
		message.inMsgState = ChatMessage.STATE_UPLOADING;
		message.inUUID = UUID.randomUUID().toString();
		message.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		if(showType == ChatMessage.TYPE_PHOTO){
			message.setPicture(content);
		} else if(showType == ChatMessage.TYPE_AUDIO){
			message.setAudio(content);
		} else {
			message.setContent(content);
		}
		return message;
	}
	// 创建消息
	private IMessage createNoFriendMessage(int showType,int pmid,int to,String content){
		IMessage message = new IMessage();
		message.setFromUid(IAuth.getInstance().loadUserInfo().getUid());
		message.setGender(IAuth.getInstance().loadUserInfo().getGender());
		message.setToUid(to);
		message.setPmid(pmid);
		message.setContent(content);
		message.setComMsg(true);
		message.setShowType(showType);
		message.setMyType(-1);
		message.setDateline(System.currentTimeMillis()/1000);
		message.inMsgState = ChatMessage.STATE_UPLOADING;
		message.inUUID = UUID.randomUUID().toString();
		message.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		if(showType == ChatMessage.TYPE_PHOTO){
			message.setPicture(content);
		} else if(showType == ChatMessage.TYPE_AUDIO){
			message.setAudio(content);
		} else {
			message.setContent(content);
		}
		return message;
	}
	private IMessage createShareMessage(int showType,int pmid,int to,String content,int discuzId,int topicId){
		IMessage message = new IMessage();
		message.setFromUid(IAuth.getInstance().loadUserInfo().getUid());
		message.setToUid(to);
		message.setPmid(pmid);
		message.setContent(content);
		message.setComMsg(true);
		message.setShowType(showType);
		message.setMyType(1);
		message.setDiscuzId(discuzId);
		message.setTopicId(topicId);
		message.setDateline(System.currentTimeMillis()/1000);
		message.inMsgState = ChatMessage.STATE_UPLOADING;
		message.inUUID = UUID.randomUUID().toString();
		message.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		if(showType == ChatMessage.TYPE_PHOTO){
			message.setPicture(content);
		} else if(showType == ChatMessage.TYPE_AUDIO){
			message.setAudio(content);
		} else {
			message.setContent(content);
		}
		return message;
	}
	
	/**
	 * 发送文本消息
	 * @param pmid 会话id
	 * @param to 接收人uid
	 * @param content
	 */
	public void sendTextMessage(int pmid, int to,String content){
		IMessage message = createMessage(IMessage.TYPE_TEXT,pmid,to,content);
		mMessages.add(message);
		mListView.setSelection(mListView.getBottom());
		if(!Tools.hasInternetConnection(mActivity)){
			ToastUtils.showToast(mActivity, Define.MSG_NO_NETWORK);
			message.inMsgState = ChatMessage.STATE_FAILURE;
			mHandler.obtainMessage(0, findIndexByUUID(message.inUUID), 0).sendToTarget();
			return;
		}
		
		// 发送请求
		RequestParams params =new RequestParams();
		params.put("pmid", pmid+"");
		params.put("fuid", to+"");
		params.put("content", content);
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, new MessageResponseHandler(message.inUUID));
	}

	
	public void resendTextMessage(int index){
		IMessage message = mMessages.get(index);
		message.inMsgState = IMessage.STATE_UPLOADING;
		mAdapter.updateView(index);
		if(!Tools.hasInternetConnection(mActivity)){
			ToastUtils.showToast(mActivity, Define.MSG_NO_NETWORK);
			message.inMsgState = ChatMessage.STATE_FAILURE;
			mHandler.obtainMessage(0, findIndexByUUID(message.inUUID), 0).sendToTarget();
			return;
		}
		// 发送请求
		RequestParams params = new RequestParams();
		params.put("pmid", message.getPmid()+"");
		params.put("fuid", message.getToUid()+"");
		params.put("content", message.getContent());
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, new MessageResponseHandler(message.inUUID));
	}
	
	/**
	 * 发送图片消息
	 */
	public void sendPhotoMessage(final int pmid, final int to,String path){
		
		final IMessage message = createMessage(IMessage.TYPE_PHOTO,pmid,to,path);
		mMessages.add(message);
		mListView.setSelection(mListView.getBottom());
		
		ImageRequest request = new ImageRequest(mActivity);
		request.setUploadUrl(Constants.URL_IM_UPLOAD_PICTURE);
		request.uploadMsgImage(new File(path), new UploadListener(){

			@Override
			public void start() {
				//TODO
			}
			
			@Override
			public void success(Photo photo) {
				// 发送请求
				RequestParams params = new RequestParams();
				params.put("pmid", pmid+"");
				params.put("fuid", to+"");
				params.put("image", photo.getUrl());
				params.put("width", photo.getWidth()+"");
				params.put("height", photo.getHeight()+"");
				SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
				SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, new MessageResponseHandler(message.inUUID));
			}

			@Override
			public void failure(int errorCode, String errorMsg) {
				int index = findIndexByUUID(message.inUUID);
				if(index != -1){
					message.inMsgState = ChatMessage.STATE_FAILURE;
					mHandler.obtainMessage(0, index, 0).sendToTarget();
				}
			}
		});
	}
	
	/**
	 * 发送图片消息
	 */
	public void resendPhotoMessage(int index){
		
		final IMessage message = mMessages.get(index);
		message.inMsgState = IMessage.STATE_UPLOADING;
		mAdapter.updateView(index);
		
		
		ImageRequest request = new ImageRequest(mActivity);
		request.setUploadUrl(Constants.URL_IM_UPLOAD_PICTURE);
		request.uploadMsgImage(new File(message.getPicture()), new UploadListener(){

			@Override
			public void start() {
				//TODO
			}
			
			@Override
			public void success(Photo photo) {
				// 发送请求
				RequestParams params = new RequestParams();
				params.put("pmid", message.getPmid()+"");
				params.put("fuid", message.getToUid()+"");
				params.put("image", photo.getUrl());
				params.put("width", photo.getWidth()+"");
				params.put("height", photo.getHeight()+"");
				SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
				SingtonAsyncHttpClient.getInstance().post(Constants.URL_SEND_IM_MESSAGE, params, new MessageResponseHandler(message.inUUID));
			}

			@Override
			public void failure(int errorCode, String errorMsg) {
				int index = findIndexByUUID(message.inUUID);
				if(index != -1){
					message.inMsgState = ChatMessage.STATE_FAILURE;
					mHandler.obtainMessage(0, index, 0).sendToTarget();
				}
			}
		});
	}
	
	/**
	 * 发送音频
	 */
	public void sendAudioMessage(){
		
	}
	//
	
	void handlerText(int index,JSONObject response){
		IMessage message = null;
		try {
			message = mMessages.get(index);
			int ret = response.getInt("ret");
			if (ret == 0) {
				JSONArray result = response.getJSONArray("result");
				JSONObject object = result.getJSONObject(0);
				long dateline = object.getLong("dateline");
				int lastid = object.getInt("lastid");
				int pmid = object.getInt("pmid");
				int msgid = object.getInt("msgid");
				
				SessionBean session = mActivity.getCurrentSession();
				session.setPmid(pmid);
				session.setDateline(dateline);
				session.setMsgid(msgid);
				session.setContent(message.getContent());
				int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0)-session.getUnreadCount();
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount);
				session.setShowStatus(0);
				SessionDao.save(mActivity, session);
				MessageChannel.get().sendSession(session);
				
				message.setPmid(pmid);
				message.setLastid(lastid);
				message.setDateline(dateline);
				message.setMsgId(msgid);
				message.inMsgState = ChatMessage.STATE_NORMAL;
				message.setDateline(System.currentTimeMillis()/1000);
				// 存本地库
//				MessageDao.save(mActivity.getApplicationContext(), message);
				MessageDao.judgeIsConnection(mActivity.getApplicationContext(), message);
				isConnect(message);
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}  else if(ret == Define.REQ_OFFLINE){
				//mAlertOfflineDialog.show();
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, Define.REQ_OFFLINE).sendToTarget();
			} else if(ret == 6){ 
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
				//Toast.makeText(mContext,"聊天室已经关闭", Toast.LENGTH_SHORT).show();
			} else if(ret == 3){
				handleNoFriend(index, message);
			}
		} catch (JSONException e) {
			CrashHandler.e(e);
			if(message != null){
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}
		}
	}
	public void handleNoFriend(int index, IMessage message) {
		message.inMsgState = ChatMessage.STATE_FAILURE;
		mHandler.obtainMessage(MSG_NO_FRIEND, index, 0).sendToTarget();
	}
	public void isConnect(IMessage message) {
		if(message.getIsConnect() == 1){
			//加载中间间隔的数据
			getLoseMessages(message);
		}
	}
	public void getUnReceived(IMessage message){
		if(message == null){
			return;
		}
		RequestParams params = new RequestParams();
		params.put("pmid", message.getPmid()+"");
		params.put("flag", "0");
		params.put("lastid", message.getLastid()+"");
		params.put("limit", 1000+"");
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().get(Constants.URL_RECEIVE_IM_MESSAGE, params, new GetLoseMessageReponse(message));
	}
	
	private void getLoseMessages(IMessage message) {
		RequestParams params = new RequestParams();
		params.put("pmid", message.getPmid()+"");
		params.put("flag", "1");
		params.put("lastid", message.getLastid()+"");
		params.put("limit", (message.getMsgId() - message.getMaxMsgId() - 1)+"");
		SingtonAsyncHttpClient.getInstance().setCookieStore(IAuth.getInstance().loadCookieStore());
		SingtonAsyncHttpClient.getInstance().get(Constants.URL_RECEIVE_IM_MESSAGE, params, new GetLoseMessageReponse(message));
	}
	private class GetLoseMessageReponse extends JsonHttpResponseHandler{
		private IMessage message;
		
		public GetLoseMessageReponse(IMessage message) {
			this.message = message;
		}
			
//		@Override
//		protected Object parseObjectResponse(String responseBody)throws JSONException {
//			//Log.e("content", "responseBody");
//			Object object = super.parseResponse(responseBody);
//			if(object instanceof JSONObject){
//				JSONObject response = (JSONObject) object;
//				
//			} 
//			return object;
//		}
		
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
			try {
				int ret = response.getInt("ret");
				if(ret == 0){
					JSONObject result = response.getJSONObject("result");
					List<IMessage> data = MessageDao.adapter(result.getJSONArray("data"));
	//				if(data == null || data.size()<=0){
	//					return object;
	//				}
					//获得的间隙数据，需要存入数据库和显示
					MessageDao.sortResponse(data);
					MessageDao.saveNoRepeat(mActivity.getApplicationContext(), data);
					SessionBean session = mActivity.getCurrentSession();
					if(data.size()>0){
					IMessage lastMessage = data.get(data.size()-1);
					if(lastMessage.getShowType() == IMessage.TYPE_PHOTO){
						session.setPmid(lastMessage.getPmid());
						session.setDateline(lastMessage.getDateline());
						session.setMsgid(lastMessage.getMsgId());
						if(lastMessage.isComMsg()){
							session.setContent(IAuth.getInstance().loadUserInfo().getNickname()+"发了一张图片");
						}else{
							session.setContent(mActivity.getCurrentSession().getNickname()+"发了一张图片");
						}
						SessionDao.save(mActivity, session);
						MessageChannel.get().sendSession(session);
					} else if(lastMessage.getShowType() == IMessage.TYPE_AUDIO){
	//					handlerAudio(index,(JSONObject) object);
					} else if(lastMessage.getShowType() == IMessage.TYPE_SHARE){
						session.setPmid(lastMessage.getPmid());
						session.setDateline(lastMessage.getDateline());
						session.setMsgid(lastMessage.getMsgId());
						session.setContent(lastMessage.getContent());
						SessionDao.save(mActivity, session);
						MessageChannel.get().sendSession(session);
					}else{
						session.setPmid(lastMessage.getPmid());
						session.setDateline(lastMessage.getDateline());
						session.setMsgid(lastMessage.getMsgId());
						session.setContent(lastMessage.getContent());
						SessionDao.save(mActivity, session);
						MessageChannel.get().sendSession(session);
					}
					}
					//更改状态
					MessageDao.reSetMsgIsConnect(mActivity.getApplicationContext(), message);
					Message msg = mHandler.obtainMessage();
					msg.obj = data;
					msg.what = MSG_LOSE_INFO;
					mHandler.sendMessage(msg);
				}
			} catch(JSONException e) {
				onFailure(statusCode, headers, e, response);
			}
		}
		@Override
		public void onFailure(int statusCode, Header[] headers,
				Throwable throwable, JSONObject errorResponse) {
			CrashHandler.e(throwable);
		}
		
		@Override
		public void onFinish() {
		}
		
	}
	void handlerShare(int index,JSONObject response){
		IMessage message = null;
		try {
			message = mMessages.get(index);
			int ret = response.getInt("ret");
			if (ret == 0) {
				JSONArray result = response.getJSONArray("result");
				JSONObject object = result.getJSONObject(0);
				long dateline = object.getLong("dateline");
				int lastid = object.getInt("lastid");
				int pmid = object.getInt("pmid");
				int msgid = object.getInt("msgid");
				int mtype = object.getInt("mtype");
				
				
				SessionBean session = mActivity.getCurrentSession();
				session.setPmid(pmid);
				session.setDateline(dateline);
				session.setMsgid(msgid);
				session.setContent(message.getContent());
				int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0)-session.getUnreadCount();
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount);
				session.setShowStatus(0);
				SessionDao.save(mActivity, session);
				MessageChannel.get().sendSession(session);
				
				message.setPmid(pmid);
				message.setLastid(lastid);
				message.setDateline(dateline);
				message.setMsgId(msgid);
				message.setMyType(mtype);
//				if(mtype == 2){
//					JSONObject extend = object.getJSONObject("extends");
//					message.setTieUrl(extend.getString("url"));
//				}
				message.inMsgState = ChatMessage.STATE_NORMAL;
				message.setDateline(System.currentTimeMillis()/1000);
				// 存本地库
				MessageDao.judgeIsConnection(mActivity.getApplicationContext(), message);
				isConnect(message);
				
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}  else if(ret == Define.REQ_OFFLINE){
				//mAlertOfflineDialog.show();
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, Define.REQ_OFFLINE).sendToTarget();
			} else if(ret == 6){ 
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
				//Toast.makeText(mContext,"聊天室已经关闭", Toast.LENGTH_SHORT).show();
			}else if(ret == 3){
				handleNoFriend(index, message);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			CrashHandler.e(e);
			if(message != null){
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}
		}
	}
	
	void handlerPhoto(int index,JSONObject response){
		IMessage message = null;
		try {
			message = mMessages.get(index);
			int ret = response.getInt("ret");
			if (ret == 0) {
				JSONArray result = response.getJSONArray("result");
				JSONObject object = result.getJSONObject(0);
				long dateline = object.getLong("dateline");
				int lastid = object.getInt("lastid");
				String picture = object.getString("picture");
				int pmid = object.getInt("pmid");
				int msgid = object.getInt("msgid");
				int width = object.getInt("width");
				int height = object.getInt("height");
				
				SessionBean session = mActivity.getCurrentSession();
				CrashHandler.d(TAG , "session.getPmid():"+session.getPmid());
				session.setPmid(pmid);
				session.setDateline(dateline);
				session.setMsgid(msgid);
				session.setContent(IAuth.getInstance().loadUserInfo().getNickname()+"发了一张图片");
				int unReadCount = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0)-session.getUnreadCount();
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, unReadCount);
				session.setShowStatus(0);
				SessionDao.save(mActivity, session);
				MessageChannel.get().sendSession(session);
				
				message.setPmid(pmid);
				message.setLastid(lastid);
				message.setDateline(dateline);
				message.setMsgId(msgid);
				message.setPicture(picture);
				message.inMsgState = ChatMessage.STATE_NORMAL;
				message.setDateline(System.currentTimeMillis()/1000);
				message.setWidth(width);
				message.setHeight(height);
				// 存本地库
				MessageDao.judgeIsConnection(mActivity.getApplicationContext(), message);
				isConnect(message);
				
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}  else if(ret == Define.REQ_OFFLINE){
				//mAlertOfflineDialog.show();
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, Define.REQ_OFFLINE).sendToTarget();
			} else if(ret == 6){ 
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
				//Toast.makeText(mContext,"聊天室已经关闭", Toast.LENGTH_SHORT).show();
			}else if(ret == 3){
				handleNoFriend(index, message);
			}
		} catch (JSONException e) {
			e.printStackTrace();
			CrashHandler.e(e);
			if(message != null){
				message.inMsgState = ChatMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}
		}
	}
	
	void handlerAudio(int index,JSONObject response){
		
	}
	
	public int findIndexByUUID(String uuid){
		int index = mMessages.size()-1;
		for (; index >= 0; index--) {
			if(mMessages.get(index).inUUID.equals(uuid)){
				break;
			}
		}
		return index;
	}
	
	public void destory(){
		//TODO
	}
	
	class MessageResponseHandler extends JsonHttpResponseHandler{
		
		private String mUUid;
		
		public MessageResponseHandler(String uuid) {
			mUUid = uuid;
		}
		
//		@Override
//		protected Object parseResponse(String responseBody)throws JSONException {
//			Object object = super.parseResponse(responseBody);
////			CrashHandler.d(TAG, "old : "+((JSONObject)object).toString());
//			// 这里还是异步的
//			if (object != null && object instanceof JSONObject) {
//				
//			}
//			return object;
//		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			int index = findIndexByUUID(mUUid);
			if(index != -1){
				IMessage message = mMessages.get(index);
				if(message.getShowType() == IMessage.TYPE_PHOTO){
					handlerPhoto(index, response);
				} else if(message.getShowType() == IMessage.TYPE_AUDIO){
					handlerAudio(index, response);
				} else if(message.getShowType() == IMessage.TYPE_SHARE){
					CrashHandler.d(TAG, "share : "+ response.toString());
					handlerShare(index, response);
				}else{
					handlerText(index, response);
				}
			}
		}
		
		@Override
		public void onFailure(int statusCode, Header[] headers,
				Throwable throwable, JSONObject errorResponse) {
			int index = findIndexByUUID(mUUid);
			if(index != -1){
				IMessage message = mMessages.get(index);
				message.inMsgState = IMessage.STATE_FAILURE;
				mHandler.obtainMessage(0, index, 0).sendToTarget();
			}
		}
	}
 	
	// 刷新前端
	static class RefreshHandler extends Handler{
		private SoftReference<ChatSessionService> ref;
		
		public RefreshHandler(ChatSessionService target) {
			ref = new SoftReference<ChatSessionService>(target);
		}
		@Override
		public void handleMessage(Message msg) {
			ChatSessionService service = ref.get();
			if(service == null) return;
			if(msg.what == MSG_LOSE_INFO){
				List<IMessage> messages = (List<IMessage>) msg.obj;
				service.mMessages.addAll(messages);
				service.mListView.setSelection(service.mListView.getBottom());
			}else if(msg.what == MSG_NO_FRIEND){
				service.mAdapter.updateView(msg.arg1);
				SessionBean bean = service.mActivity.getCurrentSession();
				IMessage message = service.createNoFriendMessage(0, bean.getPmid(), bean.getFuid(), "");
				service.mMessages.add(message);
				service.mListView.setSelection(service.mListView.getBottom());
			}else{
				service.mAdapter.updateView(msg.arg1);
				if(msg.arg2 == Define.REQ_OFFLINE){
					if(service.mActivity.mOfflineView!= null){
						service.mActivity.mOfflineView.show();
					}
				}
			}
			
		}
	}
	
}
